package com.huiquan.section.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.huiquan.analysis.domain.User;
import com.huiquan.framework.base.BaseService;
import com.huiquan.framework.base.ReturnCode;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.dao.StaticDataDao;
import com.huiquan.framework.domain.StaticData;
import com.huiquan.framework.utils.GetListUtil;
import com.huiquan.framework.utils.ReturnUtil;
import com.huiquan.section.dao.SectionDao;
import com.huiquan.section.dao.SectionHospitalDao;
import com.huiquan.section.domain.Section;
import com.huiquan.section.domain.SectionHospital;

@Service
public class SectionHospitalService extends BaseService {

	@Autowired
	private SectionHospitalDao sectionHospitalDao;
	@Autowired
	private SectionDao sectionDao;
	@Autowired
	private StaticDataDao staticDataDao;
	public ModelAndView list(String startStr, String nameKey, String exactSearchFlag,String countPerPageStr,String keyWord) {

		Map<String, Object> param = new HashMap<>();
		if (nameKey != null && !nameKey.isEmpty()) {
			if (exactSearchFlag != null && exactSearchFlag.equals("1")) {
				param.put("hospitalName", nameKey);
			} else {
				param.put("hospitalName", "%" + nameKey + "%");
			}
		}
		if (keyWord != null && !keyWord.isEmpty()) {
			if (exactSearchFlag != null && exactSearchFlag.equals("1")) {
				param.put("name", keyWord);
			} else {
				param.put("name", "%" + keyWord + "%");
			}
		}
		int totalSize = sectionHospitalDao.retrieveSize(param);

		Map<String, Integer> pageNo ;
		if (countPerPageStr != null && !countPerPageStr.isEmpty()) {
			int countPerPage = Integer.parseInt(countPerPageStr);
			pageNo = GetListUtil.getPageNoParam(totalSize, startStr, countPerPage);
			param.put("countPerPage", countPerPage);
		} else {
			pageNo = GetListUtil.getPageNoParam(totalSize, startStr);
		}
		int endPage = pageNo.get("endPage");
		int start = pageNo.get("start");
		int startIndex = pageNo.get("startIndex");

		List<SectionHospital> list = new ArrayList<>();

		if (startIndex < totalSize) {
			param.put("startIndex", startIndex);
			list = sectionHospitalDao.retrievesList(param);
		}

		Map<String, String> showSearch = new LinkedHashMap<>();
		showSearch.put("nameKey", "医院名称");
		showSearch.put("keyWord", "科室名称");

		Map<String, Object> map = GetListUtil.getReturnMap2(totalSize, start, startIndex, endPage, list, null);
		//查询是否含有新增了同义词但没有新增其他的科室图片之类的
		List<StaticData> sds = staticDataDao.retrieveByCode("SECTION_ADD_WARN");
		List<StaticData > warnList = new ArrayList<>();
		if(sds!=null && sds.size()>0){
			for(StaticData sd :sds){
				warnList.add(sd);
			}
		}
		if(warnList.size()>0){
			map.put("warn", "1");
			map.put("warnList", warnList);
		}
		map.put("showSearch", showSearch);
		
		return new ModelAndView("section/index", map);
	}

	public ModelAndView edit(String id) {
		Map<String, Object> map = new HashMap<>();
		if(StringUtils.isNotBlank(id)){
			Map<String, Object> param = new HashMap<>();
			param.put("id", id);
			SectionHospital value = sectionHospitalDao.retrieveObjectById(Long.parseLong(id));
			if(value != null){
				map.put("hospitalId", value.getHospitalId());
				map.put("hospitalName", value.getHospitalName());
				map.put("hospitalSection", value.getHospitalSection());
				map.put("sectionId", value.getSectionId());
				map.put("id", value.getId());

			}
			
		}
		return new ModelAndView("section/section_hospital_edit", map);
	}
	
	
	public ReturnData sectionHospitalAdd(String id,String hospitalId,String hospitalName,String hospitalSection,String sectionId,String changeFlag,User user){
		//只有修改。没有新增
		List<Section> sts = sectionDao.retrieveList();
		Map<String, Long> ksNameAndSectionId = new HashMap<>();
		//获取所有已经存在的科室名称对应编号
		for(Section st :sts){
			ksNameAndSectionId.put(st.getName(), st.getId());
		}
		SectionHospital oldValue = sectionHospitalDao.retrieveObjectById(Long.parseLong(id));
		Map<String, Object > param = new HashMap<>();
		param.put("hospitalId", hospitalId);
		param.put("hospitalName", hospitalName);
		param.put("hospitalSection", hospitalSection);
		param.put("id", id);
		String newSection = "";
		String oldSection = ksNameAndSectionId.get(oldValue.getSectionId())+"";
		if(StringUtils.isBlank(sectionId)){
			newSection = "0";
		}else if(ksNameAndSectionId.get(sectionId) != null){
			newSection = ksNameAndSectionId.get(sectionId)+"";
		}else{
			//不存在需要新增
			Section value = new Section();
			value.setCnt(1);
			value.setDisable("0");
			value.setModifierId(user.getUserId());
			value.setName(sectionId);
			value.setSexAgeFlag(0);
			value.setSex(0);
			value.setAge("");
			Long section = sectionDao.insert(value);
			newSection = section+"";
		}
		param.put("newSection", newSection);
		param.put("modifierId", user.getUserId());
		sectionHospitalDao.updateById(param);
		if(StringUtils.equals("1", changeFlag)){
			param.clear();
			param.put("newSection", newSection);
			param.put("oldSection", oldSection);
			param.put("modifierId", user.getUserId());
			sectionHospitalDao.updateBySection(param);
		}
		checkData();
		return ReturnUtil.success();
	}
	
	private void checkData(){
		//校验医院对应科室是否在科室图片名称中
		List<String> checkHospital =  sectionHospitalDao.checkHospitalImage();
		StringBuffer errHospitalList = new StringBuffer();
		if(checkHospital != null && checkHospital.size()>0){
			for(String sc :checkHospital){
				if(errHospitalList.length()==0){
					errHospitalList.append("以下医院科室对应科室不在科室图片的科室名称中");
				}
				errHospitalList.append(sc+";");
			}
		}
		if( errHospitalList.length()>0){
			throw new RuntimeException(errHospitalList.toString());
		}
	}
	
	

	/**
	 * 批量导入
	 * 
	 * @param user
	 * @param zipFile
	 * @return
	 * @throws IOException
	 */
	public ReturnData insertBatch(User user, MultipartFile file) throws IOException {
		if (file != null) {		// 获取文件流，解析文件
			InputStream textIn = file.getInputStream();
			InputStreamReader read = new InputStreamReader(textIn, "UTF-8"); // 考虑到文本编码
			BufferedReader bf = new BufferedReader(read);
			String line = null;
			String s[] = null;
			sectionHospitalDao.deleteAll();
			while ((line = bf.readLine()) != null) {
				s = line.split("\t");
				String hospitalId = s[0]==null?"":s[0];
				String hospitalName = s[1]==null?"":s[1];
				String sectionName =  s[2]==null?"":s[2];
				String address =  s[3]==null?"":s[3];
				String hospitalGrade =  s[4]==null?"":s[4];
				String hospitalLevel =  s[5]==null?"":s[5];
				String hospitalDetail = s[6]==null?"":s[6];
				String hospitalImage =  s[7]==null?"":s[7];
				String phoneNumber =  s[8]==null?"":s[8];
				String province =  s[9]==null?"":s[9];
				String city =  s[10]==null?"":s[10];
				String region =  s[11]==null?"":s[11];
				String longitude =  s[12]==null?"":s[12];
				String latitude =  s[13]==null?"":s[13];
				String score =  s[14]==null?"":s[14];
				String isRegister =  s[15]==null?"":s[15];
				String addressDetail=  s[16]==null?"":s[16];
				if("6504".equals(hospitalId)){
					System.out.println();
				}
				Map<String, Object> param = new HashMap<>();
				param.put("hospital_id", hospitalId);
				param.put("hospital_name", hospitalName);
				param.put("address", address);
				param.put("address_detail", addressDetail);
				param.put("hospital_grade", hospitalGrade);
				param.put("hospital_level", hospitalLevel);
				param.put("hospital_detail", hospitalDetail);
				param.put("hospital_image", hospitalImage);
				param.put("phone_number", phoneNumber);
				param.put("province", province);
				param.put("city", city);
				param.put("region", region);
				param.put("longitude", longitude);
				param.put("latitude", latitude);
				param.put("score", score);
				param.put("is_register", isRegister);
				long id = sectionHospitalDao.insertHospital(param);;
				//解析医院科室名称
				String[] sections = sectionName.split("、");
				for(String section:sections){
					if(StringUtils.isNotBlank(section)){
						param.clear();
						param.put("hospital_id", id);
						param.put("hospital_section", section);
						param.put("modifier_id", user.getUserId()+"");
						sectionHospitalDao.insertRelat(param);
					}
				}
			}
			//通过科室同义词更新对应这边的科室名称
			sectionHospitalDao.updateSectionBySynonymy();
			if(bf != null){
				bf.close();
			}
			if(read != null){
				read.close();
			}
			//校验国家对应科室是否在科室图片名称中
			checkData();
			//如果失败,删除有可能添加的section的记录
			sectionDao.deleteSectionInvalid();
			return ReturnUtil.success("成功");
		} else {
			ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
			rc.setDesc("文件有误");
			return ReturnUtil.fail(rc);
		}
	}
	
	public void deleteWarn(String id,User user){
		staticDataDao.deleteWarn(id);
	}
}
